package cn.itcast.Thread;

import java.util.concurrent.*;

/**
 * @Author : 叶荻风
 * @create : 2024/8/15 19:53
 */
public class ThreadPoolTest {
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        Future<Integer> f1 = pool.submit(new ReturnTask(10000));
        Future<Integer> f2 = pool.submit(new ReturnTask(10000));
        Future<Integer> f3 = pool.submit(new ReturnTask(10000));

        try {
            System.out.println("Result from task 1: " + f1.get());
            System.out.println("Result from task 2: " + f2.get());
            System.out.println("Result from task 3: " + f3.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    static class ReturnTask implements Callable<Integer>{

        private final long sleepTimeMillis;
        public ReturnTask(long sleepTimeMillis) {
            this.sleepTimeMillis = sleepTimeMillis;
        }
        @Override
        public Integer call() throws Exception {
            System.out.println("Task started by " + Thread.currentThread().getName());
            try {
                Thread.sleep(sleepTimeMillis);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw e;
            }
            System.out.println("Task finished by " + Thread.currentThread().getName());
            return 1;
        }

    }
}
